#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#define NUM 1024
#define SIZE 128
#define SEP " "
char command_line[NUM];
char* command_args[SIZE];
char env_buffer[NUM];
void ChangeDir(const char* new_path)
{
  chdir(new_path); 
}

void PutEnvInMyshell(char* new_env)
{
  putenv(new_env); 
}

int main()
{
  while(1)
  {
    printf("[张三@我的主机名 当前目录]# ");
    fflush(stdout);
    memset(command_line,'\0',sizeof(command_line)*sizeof(char));
    fgets(command_line,NUM,stdin);
    command_line[strlen(command_line)-1]='\0';
    command_args[0]=strtok(command_line,SEP);
    int index=1;
    if(strcmp(command_args[0],"ls")==0)
      command_args[index++]=(char*)"--color=auto";

    while(command_args[index++] = strtok(NULL,SEP));
    
   // for(int i=0;i<index;i++)
   // {
   //   printf("%d:%s\n",i,command_args[i]);
   // }
    if(strcmp(command_args[0],"cd")==0 && command_args[1]!=NULL)
    {
      ChangeDir(command_args[1]);
      continue;
    }
    
    if(strcmp(command_args[0],"export")==0 && command_args[1]!=NULL)
    {
      strcpy(env_buffer,command_args[1]);
      PutEnvInMyshell(env_buffer);  
      continue;
    }
    pid_t id=fork();
    if(id==0)
    {
      execvp(command_args[0],command_args);
      exit(1);
    }
    int status=0;
    pid_t ret=waitpid(id,&status,0);
    if(ret>0)
    {
      printf("gitee提交有问题，等待子进程成功:sig:%d,code:%d\n",status & 0x7F,(status>>8)&0xFF);
    }
  }
  return 0;
}
